package com.bwie.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.domain.User;
import com.bwie.mapper.UserMapper;
import com.bwie.utils.MD5Utils;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: lrz
 * @Date: 2024/10/31 14:27
 * @Description:
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override
    public R login(LoginInfoVo loginInfoVo) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", loginInfoVo.getUserName());
        User user = userMapper.selectOne(userQueryWrapper);
        if(user==null){
            return R.ERROR(500,"用户不存在");
        }
        String encrypt = MD5Utils.encrypt(loginInfoVo.getUserPass());
        System.out.println("密码加密："+encrypt);
        if(!user.getPassword().equals(encrypt)){
            return R.ERROR(500,"密码不正确");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", user.getId())
                .claim("userName", user.getUsername())
                .compact();
        String key = "token:"+user.getId();
        stringRedisTemplate.opsForValue().set(key,token,30, TimeUnit.MINUTES);
        user.setToken(token);
        user.setPassword(null);
        return R.OK(user);
    }
}
